package com.hp.activiti.service;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hp.activiti.annotation.ApiOpt;
import com.hp.activiti.model.LogInfo;

/**
 * @Description:操作日志aop记录
 * @author hp
 * @date 2019年6月27日 上午11:07:06
 */
@Aspect
@Component
public class LogAopService {
	
	@Autowired
	private LogInfoService logInfoService;
	
	/**
	  *  获取调用注解ApiOpt 的入参数和返回结果 写入日志系统
	 * @date 2019年6月28日 下午5:59:47
	 */
	@AfterReturning(value="@annotation(apiOpt)",returning = "keys")
	public void afterTest(JoinPoint point, ApiOpt apiOpt,Object keys){
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		String apiUri = request.getRequestURI();
		String ipStr = request.getRemoteAddr();
		
		String reqMsg = JSONArray.toJSONString(point.getArgs());
		String resMsg = JSONObject.toJSONString(keys);
		String optType = apiOpt.optType().name();
		Date optTime = new Date();
		String name = SecurityContextHolder.getContext().getAuthentication().getName();
		
		LogInfo info = new LogInfo();
		info.setOperateTime(optTime);
		info.setOptType(optType);
		info.setAccount(name);
		info.setReqMsg(reqMsg);
		info.setResMsg(resMsg);
		info.setApiUri(apiUri);
		info.setIp(ipStr);
		logInfoService.saveLogInfo(info);
	}

}
